import java.util.LinkedList;
import java.util.Queue;

class Solution06 {
    int[] dx = { 0, 0, -1, 1 };
    int[] dy = { 1, -1, 0, 0 };
    int m, n;

    public void solve(char[][] board) {
        m = board.length;
        n = board[0].length;
        // 对四周元素进行修改
        // 最上面最下面
        for (int j = 0; j < n; j++) {
            if (board[0][j] == 'O') {
                bfs(board, 0, j);
            }
            if (board[m - 1][j] == 'O') {
                bfs(board, m - 1, j);
            }
        }
        // 左边界右边界
        for (int i = 1; i < m - 1; i++) {
            if (board[i][0] == 'O') {
                bfs(board, i, 0);
            }
            if (board[i][n - 1] == 'O') {
                bfs(board, i, n - 1);
            }
        }
        // 最后一步，进行还原
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j] == 'O') {
                    board[i][j] = 'X';
                } else if (board[i][j] == '1') {
                    board[i][j] = 'O';
                }
            }
        }
    }

    public void bfs(char[][] board, int i, int j) {
        // 创建一个队列
        Queue<int[]> q = new LinkedList<>();
        // 入队
        q.add(new int[] { i, j });
        // 进行修改
        board[i][j] = '1';
        // 循环遍历
        while (!q.isEmpty()) {
            // 取队头元素
            int[] tmp = q.poll();
            int a = tmp[0], b = tmp[1];
            // 上下左右查找
            for (int k = 0; k < 4; k++) {
                int x = a + dx[k], y = b + dy[k];
                // 进行判断
                if (x >= 0 && x < m && y >= 0
                        && y < n && board[x][y] == 'O') {
                    // 入队列
                    q.add(new int[] { x, y });
                    board[x][y] = '1';
                }
            }
        }
    }
}